import { onMounted, ref, toValue } from 'vue'
import dayjs from 'dayjs'
import QuarterOfYear from 'dayjs/plugin/quarterOfYear'

dayjs.extend(QuarterOfYear)

export default function useInitData() {
  const data = ref<{ name: string, value: [string, number] }[]>([])
  const date = ref(0)

  const begin = dayjs().subtract(1, 'year').format('YYYY-MM-DD')
  const end = dayjs().subtract(1, 'day').format('YYYY-MM-DD')

  let value = Math.random() * 2000

  function initData() {
    let length = 300
    const oneDay = 24 * 3600 * 1000
    let now = new Date(begin).getTime()
    const d = []
    while (length--) {
      now += oneDay
      d.push({
        name: dayjs(now).format('YYYY-MM-DD'),
        value: [dayjs(now).format('YYYY-MM-DD'), rand()] as [string, number],
      })
    }
    date.value = now
    data.value = d
  }

  function rand() {
    value = value + Math.random() * 200 - 100
    return Math.abs(Math.round(value))
  }

  function start() {
    const oneDay = 24 * 3600 * 1000
    let now = toValue(date)
    now += oneDay

    if (now > new Date(end).getTime()) {
      value = Math.random() * 2000
      initData()
      return
    }
    date.value = now

    data.value.shift()
    data.value.push({
      name: new Date(now).toString(),
      value: [dayjs(now).format('YYYY-MM-DD'), rand()],
    })
  }

  onMounted(() => {
    initData()
  })

  return {
    data,
    start,
  }
}
